package com.molan.molan_music.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.molan.molan_music.config.SecurityConfig;
import com.molan.molan_music.entity.Role;
import com.molan.molan_music.entity.User;
import com.molan.molan_music.service.UserService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class JwtAuthorizationFilter extends BasicAuthenticationFilter {
    public JwtAuthorizationFilter(AuthenticationManager authenticationManager, UserService userService) {
        super(authenticationManager);
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader(SecurityConfig.HEADER_STRING);
        if(header==null || !header.startsWith(SecurityConfig.TOKEN_PREFIX)){
            chain.doFilter(request,response);
            return;
        }
        UsernamePasswordAuthenticationToken token = getAuthentication(header);
        SecurityContextHolder.getContext().setAuthentication(token);
        chain.doFilter(request,response);
    }

    private UserService userService;

    private UsernamePasswordAuthenticationToken getAuthentication(String header) {
        if(header != null){
            String username = JWT.require(Algorithm.HMAC512(SecurityConfig.SECRET.getBytes()))
                    .build()
                    .verify(header.replace(SecurityConfig.TOKEN_PREFIX,""))
                    .getSubject();
            if(username != null){
                User user = userService.loadUserByUsername(username);
                List<Role> roleList =userService.getauThorities(username);
                List<GrantedAuthority> authorityList = new ArrayList<>();
                for (Role role : roleList) {
                    System.out.println("roleName:=="+role.getRoleName());
                    authorityList.add(new SimpleGrantedAuthority(role.getRoleName()));
                }
                return new UsernamePasswordAuthenticationToken(username,null,authorityList);
            }
        }
        return null;
    }
}
